import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../index.dart';
import '../../../../home/widgets/activity_detail_bottom_sheet.dart';
import '../../../../../common/api/activity_api.dart'; // 添加ActivityApi的导入
import '../../../../../common/utils/toast_util.dart'; // 添加ToastUtil的导入
import '../../models/post_model.dart'; // 导入PostModel

class ActivityTab extends StatelessWidget {
  const ActivityTab({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFF5F5F5), // 与AppBar背景色保持一致
      child: GetBuilder<PlaysController>(
        builder: (controller) => Obx(() => SmartRefresher(
          enablePullDown: true,              // ✅ 启用下拉刷新
          enablePullUp: true,                // ✅ 启用上拉加载
          header: _buildSimpleHeader(),      // 🎨 自定义下拉刷新头部
          footer: _buildCustomFooter(),      // 🎨 自定义底部样式
          controller: controller.activityRefreshController, // 🎮 控制器绑定
          onRefresh: controller.onActivityRefresh,   // ⬇️ 下拉刷新回调
          onLoading: controller.onActivityLoading,   // ⬆️ 上拉加载回调Expected to find ']'.
          child: _buildContent(context, controller), // 🔥 构建内容
        )),
      ),
    );
  }

  /// 🏗️ 构建主内容 - 完全参照comment_tab.dart的成功模式
  Widget _buildContent(BuildContext context, PlaysController controller) {
    // 如果正在加载且没有数据，显示加载状态
    if (controller.isLoadingActivities.value && controller.activityPosts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
            ),
            const SizedBox(height: 16),
            const Text(
              '正在加载活动数据...',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    // ✅ 使用CustomScrollView + SliverGrid实现流畅滚动 - 与comment_tab.dart完全一致
    return CustomScrollView(
      slivers: [
        // 顶部间距
        SliverToBoxAdapter(
          child: SizedBox(height: MediaQuery.of(context).padding.top + 10.h),
        ),
        
        // 主要内容 - SliverGrid
        SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 16.w,
              mainAxisSpacing: 16.h,
              childAspectRatio: 0.75, // 活动卡片稍高一些
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) => _buildActivityCard(controller.activityPosts[index]),
              childCount: controller.activityPosts.length,
            ),
          ),
        ),
        
        // 底部间距
        SliverToBoxAdapter(
          child: SizedBox(height: 16.h),
        ),
      ],
    );
  }

  /// 🎨 构建单个活动卡片
  Widget _buildActivityCard(dynamic post) {
    return GestureDetector(
      onTap: () async { // 将onTap改为async
        // 🎯 在点击时请求活动详情
        try {
          // 提取活动ID
          final activityIdStr = post.id.replaceFirst('real_activity_', '');
          final activityId = int.tryParse(activityIdStr);

          if (activityId == null) {
            ToastUtil.error('活动ID格式错误');
            return;
          }

          // 🚀 调用API获取活动详情
          final response = await ActivityApi.getActivityDetail(activityId: activityId);

          if (response['status'] == 'success') {
            final responseData = response['activity'] ?? response['data'];
            if (responseData != null) {
              // 根据API响应构建新的PostModel
              final detailedActivity = PostModel(
                id: post.id,
                title: responseData['activityTitle']?.toString() ?? post.title,
                content: responseData['activityDetails']?.toString() ?? post.content,
                authorName: responseData['publisherNickname']?.toString() ?? post.authorName,
                authorAvatar: responseData['publisherAvatar']?.toString() ?? post.authorAvatar,
                images: (responseData['activityImages'] as List?)?.cast<String>() ?? post.images,
                likeCount: 0, // API可能不直接返回，使用默认值
                commentCount: 0, // API可能不直接返回，使用默认值
                timeAgo: '${responseData['activityCurrentParticipants'] ?? 0}/${responseData['activityMaxParticipants'] ?? 0}人',
                type: PostType.activity,
                authorSignature: responseData['publisherSignature']?.toString() ?? post.authorSignature,
                paymentType: (responseData['activityType'] as List?)?.join(', ') ?? post.paymentType,
                activityPublishTime: responseData['activityPublishTime']?.toString(),
                publishTime: responseData['activityPublishTime']?.toString(),
                extraData: responseData['extraData'] != null
                    ? ActivityExtraData.fromJson(responseData['extraData'] as Map<String, dynamic>)
                    : null,
                maxParticipants: responseData['activityMaxParticipants'] as int? ?? 0,
                currentParticipants: responseData['activityCurrentParticipants'] as int? ?? 0,
                location: responseData['activityLocation']?.toString() ?? post.location,
                activityType: (responseData['activityType'] as List?)?.cast<String>(),
                activityTags: (responseData['activityTags'] as List?)?.cast<String>(),
                authorId: responseData['publisherId'] as int?,
                latitude: responseData['latitude'] as double? ?? 0.0, // 添加latitude
                longitude: responseData['longitude'] as double? ?? 0.0, // 添加longitude
                gender: responseData['publisherGender']?.toString(), // 添加gender
                activityRestriction: (responseData['activityRestriction'] as List?)?.cast<String>() ?? post.activityRestriction, // 添加activityRestriction
              );
              ActivityDetailBottomSheet.show(activity: detailedActivity);
            } else {
              ToastUtil.error('活动详情数据为空');
            }
          } else {
            ToastUtil.error('获取活动详情失败: ${response['message'] ?? "未知错误"}');
            // 如果API调用失败，仍使用原始数据显示，提供更好的用户体验
            ActivityDetailBottomSheet.show(activity: post);
          }
        } catch (e) {
          ToastUtil.error('加载活动详情异常: $e');
          // 异常时也使用原始数据显示
          ActivityDetailBottomSheet.show(activity: post);
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withValues(alpha: 0.1),
              blurRadius: 4.r,
              offset: Offset(0, 2.h),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 图片区域
            if (post.images.isNotEmpty)
              AspectRatio(
                aspectRatio: 1.2,
                child: Stack(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.vertical(top: Radius.circular(12.r)),
                                        child: post.images.first.isNotEmpty && 
                         !post.images.first.contains('example.com')
                      ? CachedNetworkImage(
                          imageUrl: post.images.first,
                          fit: BoxFit.cover, // 🔥 保持比例填充，避免拉伸
                          width: double.infinity,
                          height: double.infinity, // 🔥 确保高度也填满
                              placeholder: (context, url) => Container(
                                color: Colors.grey[50],
                                // 移除loading动画，直接显示空白背景
                              ),
                              errorWidget: (context, url, error) => Container(
                                color: Colors.grey[100],
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.image_not_supported,
                                      size: 24,
                                      color: Colors.grey[400],
                                    ),
                                    const SizedBox(height: 2),
                                    Text(
                                      '图片加载失败',
                                      style: TextStyle(
                                        fontSize: 8,
                                        color: Colors.grey[500],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // 🔥 修复：大幅提高缓存分辨率解决图片模糊问题
                              memCacheWidth: 800,  // 内存缓存宽度（大幅提升）
                              memCacheHeight: 800, // 内存缓存高度（大幅提升）
                              maxWidthDiskCache: 800, // 磁盘缓存最大宽度（大幅提升）
                              maxHeightDiskCache: 800, // 磁盘缓存最大高度（大幅提升）
                              // 🔥 优化图片质量设置
                              filterQuality: FilterQuality.high, // 使用高质量过滤
                              fadeInDuration: Duration.zero, // 禁用淡入动画提升性能
                              fadeOutDuration: Duration.zero, // 禁用淡出动画
                            )
                          : Container(
                              color: Colors.grey[100],
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Icon(
                                    Icons.photo,
                                    size: 24,
                                    color: Colors.grey[400],
                                  ),
                                  const SizedBox(height: 2),
                                  Text(
                                    '暂无图片',
                                    style: TextStyle(
                                      fontSize: 8,
                                      color: Colors.grey[500],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                    ),

                  ],
                ),
              ),
            // 内容区域
            Padding(
              padding: EdgeInsets.all(6.r),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 标题行（标题 + 支付按钮）
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          post.title,
                          style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      if (post.paymentType.isNotEmpty)
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
                          decoration: BoxDecoration(
                            color: const Color(0xFFE33641),
                            borderRadius: BorderRadius.circular(3.r),
                          ),
                          child: Text(
                            post.paymentType,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 8.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                    ],
                  ),
                  SizedBox(height: 1.h),
                  // 内容
                  Text(
                    post.content,
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey[600],
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 2.h),
                  // 用户信息行
                  Row(
                    children: [
                      CircleAvatar(
                        radius: 6.r,
                        backgroundImage: post.authorAvatar.isNotEmpty 
                            ? NetworkImage(post.authorAvatar)
                            : null,
                        onBackgroundImageError: (_, __) {},
                        child: post.authorAvatar.isEmpty 
                            ? const Icon(Icons.person, size: 10)
                            : null,
                      ),
                      SizedBox(width: 3.w),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              post.authorName.isEmpty ? '未知用户' : post.authorName,
                              style: TextStyle(
                                fontSize: 9.sp,
                                color: Colors.grey[600],
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            if (post.authorSignature.isNotEmpty)
                              Text(
                                post.authorSignature,
                                style: TextStyle(
                                  fontSize: 7.sp,
                                  color: Colors.grey[400],
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                          ],
                        ),
                      ),
                      Text(
                        post.timeAgo.isEmpty ? '0/0' : post.timeAgo,
                        style: TextStyle(
                          fontSize: 9.sp,
                          color: Colors.grey[600],
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 🔧 自定义下拉刷新Header
  Widget _buildSimpleHeader() {
    return CustomHeader(
      builder: (BuildContext context, RefreshStatus? mode) {
        return Container(
          height: 60.0,
          color: const Color(0xFFF5F5F5),
          child: Center(
            child: _getHeaderWidget(mode),
          ),
        );
      },
    );
  }
  
  Widget _getHeaderWidget(RefreshStatus? mode) {
    switch (mode) {
      case RefreshStatus.idle:
        return const Text("下拉刷新活动", style: TextStyle(color: Colors.grey));
      case RefreshStatus.canRefresh:
        return const Text("松手刷新", style: TextStyle(color: Color(0xFFE33641)));
      case RefreshStatus.refreshing:
        return const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              width: 20, height: 20,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
              ),
            ),
            SizedBox(width: 8),
            Text("刷新中...", style: TextStyle(color: Color(0xFFE33641))),
          ],
        );
      case RefreshStatus.completed:
        return const Text("刷新完成", style: TextStyle(color: Colors.green));
      case RefreshStatus.failed:
        return const Text("刷新失败", style: TextStyle(color: Colors.red));
      default:
        return const Text("下拉刷新活动", style: TextStyle(color: Colors.grey));
    }
  }

  /// 🎨 构建自定义Footer - 精美的加载状态显示
  Widget _buildCustomFooter() {
    return CustomFooter(
      builder: (BuildContext context, LoadStatus? mode) {
        Widget body;
        double height = 55.0;
        
        if (mode == LoadStatus.idle) {
          body = const Text(
            "上拉加载更多活动", 
            style: TextStyle(color: Colors.grey, fontSize: 14),
          );
        } else if (mode == LoadStatus.loading) {
          body = Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: const [
              SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                ),
              ),
              SizedBox(width: 12),
              Text(
                "加载活动中...",
                style: TextStyle(color: Colors.grey, fontSize: 14),
              ),
            ],
          );
        } else if (mode == LoadStatus.failed) {
          body = const Text(
            "加载失败，点击重试",
            style: TextStyle(color: Colors.grey, fontSize: 14),
          );
        } else if (mode == LoadStatus.canLoading) {
          body = const Text(
            "松手加载更多活动",
            style: TextStyle(color: Colors.grey, fontSize: 14),
          );
        } else {
          // LoadStatus.noMore - 没有更多数据时的美化显示
          height = 80.0; // 增加高度让底部更美观
          body = Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 30,
                height: 1,
                color: Colors.grey[300],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.check_circle_outline,
                    size: 16,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(width: 6),
                  Text(
                    "已加载全部活动",
                    style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: 13,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
            ],
          );
        }
        
        return Container(
          height: height,
          alignment: Alignment.center,
          child: AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            child: body,
          ),
        );
      },
    );
  }
}